package com.inmaytide.website.mapper.system.provider;

import com.google.common.base.Joiner;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class SysPermissionMapperSQLProvider {

    public static final String TABLE_NAME = "sys_permission";

    @SuppressWarnings("unchecked")
    public String findPermissionCodesByRoleCodes(Map<String, Object> parameters) {
        Collection<String> roleCodes = (Collection<String>) parameters.get("roleCodes");
        SQL sql = new SQL().SELECT("a.*");
        sql.FROM(TABLE_NAME + " a");
        sql.LEFT_OUTER_JOIN("sys_role_permission b on a.id = b.permission_id");
        sql.LEFT_OUTER_JOIN("sys_role c on c.id = b.role_id");
        if (CollectionUtils.isNotEmpty(roleCodes)) {
            Joiner joiner = Joiner.on(",");
            List<String> list = new ArrayList<String>();
            roleCodes.forEach(s -> list.add(StringUtils.quote(s)));
            sql.WHERE(String.format("c.role_code in (%s)", joiner.join(list.iterator())));
        }
        return sql.toString();
    }

}
